package com.fengjue.controller;

import com.fengjue.common.RespBean;
import com.fengjue.common.utils.FDFSUtil;
import com.fengjue.pojo.Admin;
import com.fengjue.service.IAdminService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class AdminInfoController {

    @Value("${fdfs.web-server-url}")
    private String fdfs_url;
    @Autowired
    private IAdminService adminService;

    @Autowired
    private FDFSUtil fdfsUtil;

    @ApiOperation("更新当前用户信息")
    @PutMapping("/admin/info")
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication) {
        if (adminService.updateById(admin)) {
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                    admin,
                    null,
                    authentication.getAuthorities())
            );
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "更新用户密码")
    @PutMapping("/admin/pass")
    public RespBean updateAdminPassword(
            @RequestBody Map<String, Object> info
    ) {
        String oldpass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");

        return adminService.updateByIdAdminPassword(oldpass, pass, adminId);
    }


    @ApiOperation("更新用户头像")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "头像", dataType = "MultipartFile")})
    @PostMapping(value = "/admin/userface", consumes = "multipart/form-data")
    public RespBean updateAdminUserFace(MultipartFile file, Integer id, Authentication authentication) throws IOException {
        System.out.println("file = " + file);
        // http://192.168.0.103:8888/group1/M00/00/00/wKgAZ2BhsNaAPe-cAAB5tIQJtzA839.jpg
        String s = "http://" + fdfs_url + "/" + fdfsUtil.uploadFile(file);
//        String url = FastDFSUtils.getTrackerUrl() + filePath[0] + "/" + filePath[0];
        System.out.println("s = " + s);


        return adminService.updateAdminUserFace(s, id, authentication);


    }
}
